package com.petsbang.action;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.petsbang.action.dao.DataApplication;
import com.petsbang.common.Common;
import com.petsbang.db.DataBase;
import com.petsbang.http.DataHandler;
import com.petsbang.ui.LazyScrollView;
import com.petsbang.ui.LazyScrollView.OnScrollListener;
import com.petsbang.utils.ImageLoaderTask;
import com.petsbang.vo.PictureInfo;
import com.petsbang.vo.TaskParam;

public class FavorActivity extends Activity {

	private LazyScrollView waterfall_scroll;
	private LinearLayout waterfall_container;
	private ArrayList<LinearLayout> waterfall_items;
	private Display display;

	private int itemWidth;
	private int column_count = 3;// 显示列数
	private int page_count = 14; // 每次加载15张图片
	private int current_page = 0;
	private String pictureTag;

	public DataHandler dh;
	public DataApplication appState;
	public ProgressBar loadDataBar;
	
	
	
//	ArrayList<PictureInfo> picFavorList;
	DataBase db;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 初始化界面
		initView();
		// 下载图片相关信息

		Intent intent = FavorActivity.this.getIntent();
		Bundle bandle = intent.getExtras();
		pictureTag = bandle.getString("PictureTag");
		db = new DataBase(FavorActivity.this);
		db.open();
		getFavorThread.start();
	}

	public void initView() {
		appState = (DataApplication) getApplicationContext();

		display = this.getWindowManager().getDefaultDisplay();
		appState.setWidth(display.getWidth());
		appState.setHeight(display.getHeight());
		if (appState.getPicFavorList() != null) {
			appState.setPicFavorList(null);
		}

		// 根据屏幕大小计算每列大小
		itemWidth = display.getWidth() / column_count;
		setContentView(R.layout.main);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("bbbb");

		loadDataBar = (ProgressBar) findViewById(R.id.loadDataBar);
	}

	public void InitLayout() {
		loadDataBar.setVisibility(View.INVISIBLE);

		waterfall_scroll = (LazyScrollView) findViewById(R.id.waterfall_scroll);
		waterfall_scroll.getView();
		waterfall_scroll.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onTop() {
				// 滚动到最顶端
				Log.d("LazyScroll", "Scroll to top");
			}

			@Override
			public void onScroll() {
				// 滚动中
				Log.d("LazyScroll", "Scroll");
			}

			@Override
			public void onBottom() {
				// 滚动到最低端
				AddItemToContainer(++current_page, page_count);
			}
		});

		waterfall_container = (LinearLayout) this
				.findViewById(R.id.waterfall_container);
		waterfall_items = new ArrayList<LinearLayout>();

		for (int i = 0; i < column_count; i++) {
			LinearLayout itemLayout = new LinearLayout(this);
			LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams(
					itemWidth, LayoutParams.WRAP_CONTENT);
			itemLayout.setPadding(4, 4, 4, 4);
			itemLayout.setOrientation(LinearLayout.VERTICAL);

			itemLayout.setLayoutParams(itemParam);
			waterfall_items.add(itemLayout);
			waterfall_container.addView(itemLayout);
		}

		// 第一次加载
		AddItemToContainer(current_page, page_count);
	}

	private void AddItemToContainer(int pageindex, int pagecount) {
		int j = 0;
		// 加载所有图片路径
		ArrayList<PictureInfo> picFavorList = appState.getPicFavorList();
		if (picFavorList == null) {
			return;
		}
		int count = picFavorList.size();
		for (int i = pageindex * pagecount; i < pagecount * (pageindex + 1)
				&& i < count; i++) {
			j = j >= column_count ? j = 0 : j;
			AddImage(picFavorList.get(i), j++);
		}
	}

	private void AddImage(final PictureInfo pic, int columnIndex) {
		
		LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(this)
				.inflate(R.layout.item_for_flow_list, null);
		LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams(
				itemWidth - 8, LayoutParams.WRAP_CONTENT);
		itemParam.height = itemWidth-8;
		itemParam.bottomMargin = 6;
		
		linearLayout.setLayoutParams(itemParam);

		linearLayout.setOnClickListener(new LinearLayout.OnClickListener() {
			public void onClick(View v) {
				ArrayList<PictureInfo> picFavorList = appState.getPicFavorList();
				int index = picFavorList.indexOf(pic);

				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putInt("index", index);
				bundle.putString("PictureTag", pictureTag);
				bundle.putString("FromFlag", "FavorActivity");
				intent.putExtras(bundle);
				intent.setClass(FavorActivity.this, LovelyActivity.class);

				startActivity(intent);
			}
		});

		
		waterfall_items.get(columnIndex).addView(linearLayout);

		ImageView imageView = (ImageView) linearLayout
				.findViewById(R.id.imageview);

		String imageUrl = pic.getMiddle_url();
		TaskParam param = new TaskParam();
		param.setFilename(imageUrl);
		param.setItemWidth(itemWidth);
		ImageLoaderTask task = new ImageLoaderTask(imageView);
		task.execute(param);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 清除信息
		db.close();
//		appState.setPicList(null);
	}
	
	Handler handler = new Handler () {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what) {
			case 1:
//				Toast.makeText(FavorActivity.this, "接收到了，可以更新UI！",
//						Toast.LENGTH_LONG).show();
				InitLayout();
			}
		}
		
	};

	Thread getFavorThread = new Thread(){

		@Override
		public void run() {
			Message msg = new Message();
			getFavorPicture(pictureTag);
			msg.what = 1;
			handler.sendMessage(msg);
		}
	};
	
	
	/**
	 * 
	 * 
	 */
	
	private void getFavorPicture(String tag) {
		Cursor cursor = db.queryFavorPicture(tag);
		ArrayList<PictureInfo> picFavorList = new ArrayList<PictureInfo>();
		
		int size = cursor.getCount();
		cursor.moveToFirst();
		for (int i=0; i<size; i++) {
			PictureInfo tmpPic = new PictureInfo();
			tmpPic.setTimestamp(cursor.getInt(cursor.getColumnIndex(Common.TIMESTAMP))); // time stamp
			tmpPic.setId(cursor.getInt(cursor.getColumnIndex(Common.ITEM_ID)));        // id
			tmpPic.setTag(cursor.getString(cursor.getColumnIndex(Common.TAG)));  // tag
			tmpPic.setWidth(cursor.getInt(cursor.getColumnIndex(Common.WIDTH)));     // width
			tmpPic.setHeight(cursor.getInt(cursor.getColumnIndex(Common.HEIGHT)));    // Height
			tmpPic.setImage_width(cursor.getInt(cursor.getColumnIndex(Common.IMAGE_WIDTH)));    // Image_width
			tmpPic.setImage_height(cursor.getInt(cursor.getColumnIndex(Common.IMAGE_HEIGHT)));   // Image_height
			tmpPic.setLarge_url(cursor.getString(cursor.getColumnIndex(Common.LARGE_URL)));   // Large_url
			tmpPic.setMiddle_url(cursor.getString(cursor.getColumnIndex(Common.MIDDLE_URL)));  // Middle_url
			tmpPic.setThumbnail_url(cursor.getString(cursor.getColumnIndex(Common.THUMBNAIL_URL))); // Thumbnail_url
			tmpPic.setShare_url(cursor.getString(cursor.getColumnIndex(Common.SHARE_URL))); // Thumbnail_url
			tmpPic.setComments_count(cursor.getInt(cursor.getColumnIndex(Common.COMMENTS_COUNT)));   // Comments_count
			tmpPic.setDesc(cursor.getString(cursor.getColumnIndex(Common.DESCRIPTION)));          // Desc
			picFavorList.add(tmpPic);
			cursor.moveToNext();
		}
		appState.setPicFavorList(picFavorList);
		
		cursor.close();
	}

}